var express = require('express');
var app = express();

var http = require('http').Server(app);
var io = require('socket.io')(http);
var child_process = require('child_process');


app.use(express.static(__dirname + '/app'));
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    //res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

//var pd = require('./protocol.js');
http.listen(9000, function () {
    console.log('listening on *:9000');
});

app.get('/', function (req, res) {
    res.send('<h1>Welcome Realtime TCP server of master node </h1>');
});


//启动一个端口进程
app.get('/port_start/:port',function(req,res){

});
//重启一个端口进程
app.get('/port_restart/:port',function(req,res){

});
//停止一个端口进程
app.get('/port_stop/:port',function(req,res){

});
//获取进程端口列表
app.get('/port_list',function(req,res){

});
//向端口设备发布命令
app.post('/port_command/:port/:deviceid',function(req,res){

});

app.post('/protocol/VIP',function(req,res){
  
});


// console.log(pd.protocol_define.port);
/*
var process_child = child_process.fork(__dirname+'/cc.js');// -p '+ pd.protocol_define.port);
process_child.send( pd.protocol_define);


//接收协议文件和端口,并且启动服务器
app.post('/protocol',function(req,res){
	//var obj = req.body;
	//获取对方的IP地址
	var obj = {};
	obj.protocol={ 
		         start:{len:1,c:0x69}, 
		         deviceid:{offset:2,len:4}, 

		         cmd:{offset:3,len:1},
		         headfields:{
		             len:8,field:[
                         {name:"time",offset:9,len:6},
                         {name:"version",offset:15,len:1},
                         {name:"aftercmd",offset:16,len:1}
		             ]
		         },
			     contentlen:{offset:6,len:1,includehead:0}, //includehead 为0 不包含头部 1 包含头部和其他
				 crc:{len:2},
				 cmd:{offset:3,len:1},
			     contentlen:{offset:6,len:1},

			     bodyfields:[
			         {
                         //type: string float double uint32 int32 uint16 int16 int8 uint8
						 //ftype bige 大端格式数据 lite小端数据格式
			             cmd:1,
			             field:[
			            {name:"temp", type:"float", ftype:"bige", len:4},
			            {name:"high",type:"int16", ftype:"bige",len:2},
			            {name:"a",ftype:"float",ftype:"bige",len:4}]
			         },
                     {
                         cmd:2,
                         field:[
                             {name:"temp2",type:"float",ftype:"bige",len:2},
                             {name:"tt",type:"string",ftype:"",len:4}
                         ]   
                     },
			         {
			             cmd:4,
			             field:[
                             {name:"test",type:"integer",ftype:"bige",len:4}
			             ]
	                 }
			     ],
			     crc:{len:2},
			     end:{len:1,c:0x16}
	};
	obj.url = "http://192.168.1.237:10011/postdata";//post 数据的远程地址
	obj.ipaddr = "192.168.1.237";  //数据推流到另外的服务器或者服务器组
	obj.port   = "8052"; //tcp端口启动为8052

	//查询端口是否已经占用
	//启动程序
	var process_child = child_process.fork(__dirname+'/cc.js -i '+ obj.ipaddr + " -p " +  obj.port);
    process_child.send({ protocol: obj.protocol,url:obj.url});
});


io.on('connection', function (socket) {

    function send_gateway_status(){
        if(db_gateway==null){
            return;
        }
        if(db_gateway.size > 0){
            for (let [key, value] of db_gateway) {  
                var data = {};
                data.gid = key;
                data.name = value.name;
                data.online = value.online;
                data.config = value.config;
                socket.emit("gateway_status", data);
                //socket.broadcast.to("users").emit("gateway_config", data);
                console.log(data);  
            } 
        }
    }
    socket.on('user', function (data) {
        socket.name = data.name; 
        socket.gid = 0; //网关id赋值，0 非网关id
        socket.is_gateway = false;
        socket.join("users");
        //对链接上来的客户发送网关状态
        send_gateway_status();
        console.log(socket.name + '加入了协同视察环境');
    });


    socket.on('disconnect', function () {
        if (socket.is_gateway == true) {
            //网关下线
            var obj = device_get(socket.gid);
            if (obj != null) { //给用户通知网关下线
                obj.online = 0;
                var data = {};
                data.gid = obj.gid;
                data.name = obj.name;
                data.online =0;
                socket.broadcast.to("users").emit('gateway_status', data);
            }
        }
    });
    //网关上线
    socket.on('gateway', function (data) {
        console.log("网关要求注册:%d-%s", data.gid,data.name);
        socket.gid = data.gid; //网关id赋值
        socket.is_gateway = true;
        socket.name = data.name; //名称赋值
       // console.log(data);
        device_set(data.gid,data.name,data.config,socket); //保存value
        
        //如果有权限,要求网关发送配置
        //给所有用户发送网关上线
        var obj = {};
        obj.gid = data.gid;
        obj.name = data.name;
        obj.online = 1;
        obj.config = data.config;
        //socket.emit("gateway_status", obj);
        socket.broadcast.to("users").emit("gateway_status",obj);
    });
    

 

    //客户端要求播放流,权限处理
    socket.on('stream_start', function (data) {
        console.log("client ask stream %s", data.deviceid);
        let gid = data.gid;
        let gateway = device_get(data.gid);
        if (gateway == null || gateway.online == 0){
            socket.emit("msg-error", "网关没有启动");
            return;
        }
        var sock = gatewau.sock;
        //查找网关，启动转发
        sock.emit("stream_start", data);
        socket.broadcast.to("users").emit('stream_start',data);
    });
    socket.on('stream_restart', function (data) {
        console.log("client ask restartstream %d", data.gid);
    });

    socket.on('stream_leave', function (data) {
        //socket.leave(request.item);
    });
    //停止流，admin可以发送
    socket.on('stream_stop', function (data) {
        //这里要修改减去人数，判断无人再看图像，客户端可以停掉
        console.log("client ask restartstream %d-%d", data.gid,data.deviceid);
       
     });

});
*/